<template>
  <div class="aside-nav">
    <div class="logo-wrapper">
      <div class="logo-img"></div>
      <h1>精准教学平台管理中心</h1>
    </div>
    <div class="link-wrapper">
      <router-link
        v-for="({ name, path }, index) in navList"
        :key="path"
        :to="path"
        v-slot="{ href, isActive }"
      >
        <a class="link-item" :class="{ active: isActive }" :href="href">
          <img
            :src="
              require(`@/assets/image/aside/icon-${index + 1}${
                isActive ? '-active' : ''
              }.png`)
            "
          />
          <span>
            {{ name }}
          </span>
        </a>
      </router-link>
    </div>
    <div class="user-info">
      <img class="bell-icon" src="@/assets/image/common/icon-bell.svg" alt="" />

      <div
        class="user-name"
        @mouseover="showDropDown = true"
        @mouseleave="showDropDown = false"
      >
        <img src="@/assets/image/common/icon-user.svg" alt="" />
        <span>
          {{ userName }}
        </span>
        <i class="el-icon-arrow-right"></i>

        <div class="drop-down" v-if="showDropDown" @click="toExit">
          <span class="item">退出</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions } from 'vuex';
import { HIDE_RIGHT_MANAGE_ROLE_LIST } from '@/utils/constant';
export default {
  name: 'AsideNav',
  data() {
    return {
      navList: [],
      showDropDown: false,
      menuLoading: false,
    };
  },
  computed: {
    ...mapState('user', ['userInfo', 'menuList', 'menuLoading']),
    ...mapState('base', ['isFromExamWeb']),
    ...mapGetters('user', ['userPermission', 'userName']),
    // 从 Vuex 中获取菜单列表，转换为导航列表
    navListFromStore() {
      if (!this.menuList || this.menuList.length === 0) {
        return [];
      }
      
      let navList = this.menuList.map(menu => ({
        name: menu.menu_name,
        path: menu.menu_path,
        icon: menu.menu_icon,
        id: menu.id
      }));
      
      // 如果用户角色在隐藏权限管理的列表中，则过滤掉权限管理选项
      if (this.userInfo && HIDE_RIGHT_MANAGE_ROLE_LIST.includes(this.userInfo.role)) {
        navList = navList.filter((e) => e.name !== '权限管理');
      }
      
      return navList;
    }
  },
  watch: {
    // 监听菜单列表变化，自动更新导航列表
    menuList: {
      immediate: true,
      handler(newMenuList) {
        if (newMenuList && newMenuList.length > 0) {
          this.updateNavList();
        }
      }
    }
  },
  async created() {
    // 如果菜单未加载，则获取菜单
    if (!this.menuList || this.menuList.length === 0) {
      await this.ensureMenusLoaded();
    } else {
      // 菜单已存在，直接更新导航列表
      this.updateNavList();
    }
  },
  methods: {
    ...mapActions('school', ['RESET_SCHOOL']),
    
    // 确保菜单已加载（如果未加载则从 Vuex action 获取）
    async ensureMenusLoaded() {
      // 如果正在加载中，等待加载完成
      if (this.menuLoading) {
        // 等待菜单加载完成（最多等待5秒）
        let waitCount = 0;
        while (this.menuLoading && waitCount < 50) {
          await new Promise(resolve => setTimeout(resolve, 100));
          waitCount++;
        }
      }
      
      // 如果菜单仍未加载，则调用 Vuex action 获取
      if (!this.menuList || this.menuList.length === 0) {
        try {
          // 登录时已经通过 fetchAllButtonPermissions 加载了完整的菜单树，不需要再调用 fetchUserMenus
          // 如果菜单树为空，才需要重新获取
          const menuTree = this.$store.getters['user/menuTree'];
          if (!menuTree || menuTree.length === 0) {
            await this.$store.dispatch('user/fetchAllButtonPermissions');
          }
        } catch (error) {
          console.error('侧边栏获取菜单失败:', error);
        }
      }
      
      // 更新导航列表
      this.updateNavList();
    },
    
    // 从 Vuex store 更新导航列表
    updateNavList() {
      if (!this.menuList || this.menuList.length === 0) {
          this.navList = [];
          return;
        }
        
      this.navList = this.menuList.map(menu => {
        // 确保路径格式正确：如果是相对路径，转换为绝对路径
        let menuPath = menu.menu_path || '';
        if (menuPath && !menuPath.startsWith('/')) {
          menuPath = '/homepage/' + menuPath;
        }
        
        return {
            name: menu.menu_name,
          path: menuPath,
            icon: menu.menu_icon,
            id: menu.id
        };
      });
          
          // 如果用户角色在隐藏权限管理的列表中，则过滤掉权限管理选项
      if (this.userInfo && HIDE_RIGHT_MANAGE_ROLE_LIST.includes(this.userInfo.role)) {
            this.navList = this.navList.filter((e) => e.name !== '权限管理');
          }
          
      console.log('侧边栏导航列表已更新，菜单数量:', this.navList.length);
    },
    
    toExit() {
      // 清除所有模块的状态（包括 sessionStorage）
      this.$store.dispatch('clearAllState');
      
      if (this.isFromExamWeb) {
        window.close();
      } else
        this.$router.push({
          path: '/login',
        });
    },
  },
};
</script>

<style lang="less" scoped>
.aside-nav {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .logo-wrapper {
    .logo-img {
      width: 100px;
      height: 100px;
      padding: 40px 0 22px;
      display: inline-block;
      background: url('@/assets/image/login/logoicon.jpg') center no-repeat;
      background-size: contain;
    }
    h1 {
      font-size: 16px;
      letter-spacing: 1px;
      color: #262626;
    }
  }
  .link-wrapper {
    padding: 38px 0;
    .link-item {
      height: 50px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #666;
      user-select: none;
      img {
        width: 20px;
        margin-right: 10px;
      }
      &.active {
        font-weight: bold;
        color: #009cff;
        background-color: #ebf5ff;
      }
      &:hover {
        background-color: #f0f5fa;
      }
    }
  }
  .user-info {
    width: 100%;
    margin-top: auto;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .bell-icon {
      margin-bottom: 25px;
      cursor: pointer;
    }
    .user-name {
      width: 150px;
      height: 44px;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 30px;
      border: 1px solid rgba(0, 0, 0, 0.2);
      border-radius: 5px;
      cursor: pointer;
      position: relative;
      span {
        display: inline-block;
        margin: 0 4px 0 10px;
        max-width: 90px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      i {
        position: relative;
        top: 2px;
      }
      .drop-down {
        padding: 10px;
        background-color: #fff;
        border-radius: 5px;
        position: absolute;
        border: 1px solid #d9d9d9;
        right: 0;
        transform: translateX(100%);
        // cursor: unset;
        box-shadow: 0 12px 10px 0 rgba(0, 0, 0, 0.1);
        .item {
          cursor: pointer;
        }
      }
    }
  }
}
</style>
